<template>
  <div class="user-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="conditions">
            <span class="card-title" style="margin-right: 40px">用户管理</span>
            <div class="condition-item">
              <span>账户：</span>
              <el-input v-model="condition.userAccount" placeholder="输入账户搜索" clearable></el-input>
            </div>
            <div class="condition-item">
              <span>状态：</span>
              <el-select v-model="condition.status" placeholder="选择用户状态">
                <el-option :value="''" label="全部">全部</el-option>
                <el-option :value="UserStatus.NORMAL" label="正常">正常</el-option>
                <el-option :value="UserStatus.LOCKED" label="已锁定">已锁定</el-option>
              </el-select>
            </div>
            <el-button type="primary" @click="handleSearch">查询</el-button>
          </div>

          <el-button type="primary" @click="handlePopCreateUserModal">添加用户</el-button>
        </div>
      </template>
      <el-table :data="userList" style="width: 100%" height="450px" @sort-change="handleSortChange">
        <el-table-column prop="userAccount" label="账号" width="180" />
        <el-table-column prop="contact" label="联系方式" width="220" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column prop="balance" label="余额" width="180" sortable="custom" />
<!--        <el-table-column prop="createDate" label="创建时间"/>-->
        <el-table-column prop="status" label="状态" >
          <template #default="scope">
            <span class="success-text" v-if="scope.row.status === UserStatus.NORMAL">正常</span>
<!--            <span class="grey-text" v-if="scope.row.status === UserStatus.DELETED">已删除</span>-->
            <span class="error-text" v-if="scope.row.status === UserStatus.LOCKED">已锁定</span>
          </template>
        </el-table-column>
        <el-table-column prop="options" label="操作" width="260">
          <template #default="scope">
            <el-button class="opt-item" type="primary" link @click="handlePopEditUserModal(scope.row)">编辑</el-button>
            <el-button class="opt-item" type="primary" link @click="handleViewToken(scope.row)">查看Token</el-button>
            <el-dropdown>
              <el-button type="primary" size="small">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-if="scope.row.status === UserStatus.NORMAL">
                    <span class="dropdown-item-span" @click="handlePopRecharge(scope.row)">充值</span>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <span class="dropdown-item-span" @click="handleResetUserPassword(scope.row)">重置密码</span>
                  </el-dropdown-item>
                  <el-dropdown-item v-if="scope.row.status === UserStatus.NORMAL">
                    <span class="dropdown-item-span"  @click="handleUpdateUserStatus(scope.row, UserStatus.LOCKED)">锁定</span>
                  </el-dropdown-item>
                  <el-dropdown-item v-if="scope.row.status === UserStatus.LOCKED">
                    <span class="dropdown-item-span"   @click="handleUpdateUserStatus(scope.row, UserStatus.NORMAL)">解锁</span>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <span class="dropdown-item-span" @click="handleResetUserToken(scope.row)">重置Token</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-block">
        <el-pagination
            :current-page="pagination.pageIndex"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <el-dialog title="添加|编辑用户" v-model="dialogVisible" width="50%">
      <el-form
          ref="userFormRef"
          :model="userState"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          status-icon>
        <el-form-item label="用户账号" prop="userAccount">
          <el-input v-model="userState.userAccount"   :disabled="editFlag"/>
        </el-form-item>
        <el-form-item label="用户密码" prop="userPassword" v-if="!editFlag">
          <el-input v-model="userState.userPassword"/>
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input v-model="userState.contact" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="userState.remark" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="saveUserLoading" @click="handleSaveUser">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="rechargeDialogVisible" title="充值" width="25%">
      <el-form
          ref="rechargeFormRef"
          :model="rechargeFormState"
          label-width="auto"
          label-position="top"
          class="demo-ruleForm"
          status-icon>
        <el-form-item label="充值账号" prop="userAccount" >
          <el-input v-model="rechargeFormState.userAccount"  :disabled="true"/>
        </el-form-item>
        <el-form-item label="充值金额" prop="amount">
          <el-input-number v-model="rechargeFormState.amount"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="rechargeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveRecharge">确定</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import {ref, nextTick} from 'vue'
import api from '../../api/index.js'
import constants from "~/common/constants.js";
import {ElMessage, ElMessageBox} from "element-plus";
import {ArrowDown} from "@element-plus/icons-vue";
import {md5} from 'js-md5'
import {uuid} from "~/common/utils.js";

const userFormRef = ref()
const UserStatus = constants.UserStatus
const pagination = ref({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
})
const condition = ref({
  userAccount: '',
  status: '',
  orderProp: '',
  order: ''
})
const dialogVisible = ref(false)
const saveUserLoading = ref(false)
const rechargeDialogVisible = ref(false)
const editFlag = ref(false)
const userList = ref([])
const userState = ref({
  userId: '',
  userAccount: '',
  userPassword: '',
  contact: '',
  remark: '',
  createDate: '',
  balance: 0,
  status: '',
})
const rechargeFormState = ref({
  userId: '',
  userAccount: '',
  amount: 0,
})
const rules = {
  userAccount: [
    { required: true, message: '请输入用户账号', trigger: 'blur' },
  ],
  userPassword: [
    { required: true, message: '请输入用户密码', trigger: 'blur' },
  ],
}
const getUserList = () => {
  userList.value = []
  // pagination.value.total = 0
  api.getUserList({
    userAccount: condition.value.userAccount || '',
    status: condition.value.status || '',
    orderProp: condition.value.orderProp,
    order: condition.value.order,
    pageIndex: pagination.value.pageIndex,
    pageSize: pagination.value.pageSize,
  }).then((res) => {
    if (res.data) {
      if (res.data.data) {
        userList.value = res.data.data
      }
      pagination.value.total = res.data.recordTotal || 0
    }
  })
}
const handleSizeChange = () => {
  console.log('handleSizeChange')
  pagination.value.pageIndex = 1
  getUserList()
}
const handleCurrentChange = (page) => {
  console.log('handleCurrentChange')
  pagination.value.pageIndex = page
  getUserList()
}
const handleSearch = () => {
  pagination.value.pageIndex = 1
  getUserList()
}
const handleSortChange = (data) => {
  condition.value.orderProp = data.prop
  condition.value.order = data.order
  handleSearch()
}
const handlePopCreateUserModal = () => {
  editFlag.value = false
  userState.value = {
    userId: '',
    userAccount: '',
    userPassword: '',
    contact: '',
    remark: '',
    createDate: '',
    balance: 0,
    status: UserStatus.NORMAL,
  }
  dialogVisible.value = true
  nextTick(() => {
    userFormRef.value.clearValidate()
  })
}
const handlePopEditUserModal = (row) => {
  editFlag.value = true
  userState.value = row
  dialogVisible.value = true
  nextTick(() => {
    userFormRef.value.clearValidate()
  })
}
const handleViewToken = (row) => {
  api.getApiToken({userId: row.userId}).then((res) => {
    if (res.data && res.data.token) {
      ElMessageBox.alert(`<span class="token-text">${res.data.token}</span>`, `账号【${row.userAccount}】API调用Token`, {
        confirmButtonText: '确定',
        'button-size': 'small',
        dangerouslyUseHTMLString: true,
        callback: () => {}
      })
    } else {
      ElMessage.error(res.message || '查询失败')
    }
  }).catch((e) => {
    ElMessage.error('查询异常')
  })
}
const handlePopRecharge = (row) => {
  rechargeFormState.value = {
    userAccount: row.userAccount,
    userId: row.userId,
    amount: 0,
  }
  rechargeDialogVisible.value = true
}
const handleSaveRecharge = () => {
  ElMessageBox.confirm(
      `确定要为账户【${rechargeFormState.value.userAccount}】充值【${rechargeFormState.value.amount}】元吗?`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    api.userRecharge({
      userId: rechargeFormState.value.userId,
      amount: rechargeFormState.value.amount
    }).then((res) => {
      if (res.code === 0) {
        ElMessage.success('充值成功')
        getUserList()
        rechargeDialogVisible.value = false
      } else {
        ElMessage.error('充值失败')
      }
    }).catch(() => {
      ElMessage.error('充值异常')
    })
  }).catch(() => {
    rechargeDialogVisible.value = false
  })
}
const handleResetUserPassword = (row) => {
  ElMessageBox.confirm(
      `确定要为账户【${row.userAccount}】重置密码吗?`,
      '提示',
      {
        'button-size': 'small',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    const pwd = uuid(16)
    api.updateUserPassword({
      userId: row.userId,
      userPassword: md5(pwd)
    }).then((res) => {
      if (res.code === 0) {
        ElMessageBox.alert(`【${row.userAccount}】新密码：${pwd}`,'重置密码成功', {
          'button-size': 'small',
          callback:() => {}
        })
      } else {
        ElMessage.error('重置密码失败')
      }
    }).catch((e) => {
      ElMessage.error('重置密码异常')
    })
  }).catch((e) => {})
}
const handleResetUserToken = (row) => {
  ElMessageBox.confirm(
      `确定要为账户【${row.userAccount}】重置API调用Token吗,重置后账户需要替换此token才可继续使用?`,
      '提示',
      {
        'button-size': 'small',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    api.createApiToken({
      userId: row.userId,
    }).then((res) => {
      if (res.code === 0) {
        ElMessage.success('操作成功')
      } else {
        ElMessage.error('操作失败')
      }
    }).catch((e) => {
      ElMessage.error('操作异常')
    })
  }).catch((e) => {})
}
const handleUpdateUserStatus = (row, status) => {
  let msg = ''
  if (status === UserStatus.NORMAL) {
    msg = `确定要【解锁】账户【${row.userAccount}】吗，解锁后账户即【可调用】API?`
  } else {
    msg = `确定要【锁定】账户【${row.userAccount}】吗，锁定后账户将【不可调用】API?`
  }
  ElMessageBox.confirm(
      msg,
      '提示',
      {
        'button-size': 'small',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    api.updateUserStatus({
      userId: row.userId,
      status,
    }).then((res) => {
      if (res.code === 0) {
        ElMessage.success('操作成功')
        getUserList()
      } else {
        ElMessage.error('操作失败')
      }
    }).catch((e) => {
      ElMessage.error('操作异常')
    })
  }).catch((e) => {})

}
const handleSaveUser = async () => {
  try {
    await userFormRef.value.validate()
    if (!userState.value.contact && !userState.value.remark) {
      ElMessage.error('联系方式和备注至少填写一个')
      return
    }
    saveUserLoading.value = true
    let res
    if (editFlag.value) {
      res = await api.updateUserInfo({
        userId: userState.value.userId,
        contact: userState.value.contact,
        remark: userState.value.remark
      })
    } else {
      res = await api.createUser({
        userAccount: userState.value.userAccount,
        userPassword: md5(userState.value.userPassword),
        contact: userState.value.contact,
        remark: userState.value.remark,
      })
    }
    saveUserLoading.value = false
    if (res.code === 0) {
      ElMessage.success('保存成功')
      dialogVisible.value = false
      pagination.value.pageIndex = 1
      getUserList()
    } else {
      ElMessage.error(res.message || '保存失败')
    }
  } catch(e){
    saveUserLoading.value = false
    ElMessage.error('保存异常')
  }
}
getUserList()
</script>

<style scoped lang="scss">
.opt-item{
  margin-right: 12px;
}
.dropdown-item-span{
  display: inline-block;
  width: 100%;
}
.pagination-block{
  padding: 20px 0 10px;
}
</style>
